﻿using System;
using NAudio.Wave;

namespace PT.NoteDetection.Wave {
    public class WaveInAudioCapture : AudioCapture {
        IWaveIn device;

        public override void Start() {
            if (IsCapturing) {
                return;
            }

            if (Output == null) {
                return;
            }

            if (device == null) {                   
                device = new WaveIn(WaveCallbackInfo.FunctionCallback());
                device.RecordingStopped += OnRecordingStopped;
                device.DataAvailable += OnDataAvailable;
            }

            device.WaveFormat = Output.WaveFormat;
            device.StartRecording();

            IsCapturing = true;
        }

        public override void Stop() {
            if (!IsCapturing) {
                return;
            }

            if (device != null) {
                device.StopRecording();
            }
        }

        void OnDataAvailable(object sender, WaveInEventArgs e) { 
            if (!IsCapturing) {
                return;
            }

            Output.Write(e.Buffer, 0, e.BytesRecorded);
            
            OnNewData();
        }

        void OnRecordingStopped(object sender, EventArgs e) {
            IsCapturing = false;
        }
    }
}
